package yanyi.community.provider;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import okhttp3.*;
import org.springframework.stereotype.Component;
import yanyi.community.dto.AccessTokenDTO;
import yanyi.community.dto.GiteeUser;

import java.io.IOException;

/**
 * gitee登陆
 * @author 98272
 */
@Component
public class GiteeProvider {
    /**
     * 获取AccessToken
     */
    public String getAccessToken(AccessTokenDTO accessTokenDTO) {
        MediaType mediaType = MediaType.get("application/json; charset=utf-8");
        OkHttpClient client = new OkHttpClient();
        RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(accessTokenDTO));
        Request request = new Request.Builder()
                .url("https://gitee.com/oauth/token?grant_type=authorization_code&code=" + accessTokenDTO.getCode()
                        + "&client_id=" + accessTokenDTO.getClient_id() + "&redirect_uri=" + accessTokenDTO.getRedirect_url() + "&client_secret=" + accessTokenDTO.getClient_secret())
                .post(body)
                .build();
        try (Response response = client.newCall(request).execute()) {
            JSONObject obj = JSONObject.parseObject(response.body().string());
            return obj.get("access_token").toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取gitee用户信息
     */
    public GiteeUser getUser(String accessToken) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url("https://gitee.com/api/v5/user?access_token=" + accessToken).build();
        try (Response response = client.newCall(request).execute()) {
            String str = response.body().string();
            GiteeUser user = JSONObject.parseObject(str, GiteeUser.class);
            return user;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
